// pages/pre-book/index.js
const {addOrder} = require('../../apiConfig/apiList/luban')
const {saveSubscribeStatus} = require('../../apiConfig/apiList/luban')
const {addressList} = require('../../apiConfig/apiList/luban')
const plugin = requirePlugin("WechatSI")
const util = require('../../utils/util')
const conf = require('../../config')
const fileUrl = conf.interface.fileUrl;
import { language } from '../../utils/record';
const {repairList} = require('../../utils/repairData');
const MAX_IMG_NUM = 9;

// 获取**全局唯一**的语音识别管理器**recordRecoManager**
const manager = plugin.getRecordRecognitionManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      schoolName: '',
      addresssId: '',
      serviceName: '',
      phone: '',
      content: '',
      picIds: [],
    },
    capture:"camera",
    selectedAddress:'',
    content: '',
    fileList: [],
    fileList2: [],
    images: [],
    lastId: 0,
    selectPhoto: true,
    recordData: {},
    buttonConf: language[0],
    bottomButtonDisabled: false,
    showPanel: false,
    actions: [],
    treeNames: '',
    showTree: false,
    addressSelectFlag: false,
    params: {
      pageNum: 1,
      pageSize: 100,
      orderByColumn: 'create_time',
      isAsc: 'desc',
    },
    columns: [
      {
        values: repairList,
        className: 'column1',
      },
      {
        values: repairList[0].children,
        className: 'column2',
        defaultIndex: 2,
      },
    ],
    addressSelect:[
      {id : "dz1",text: "dz1"},
      {id : "dz1", text:"dz1"}
    ]
  },
  showMenuList: function(){
    this.setData({ showTree: true });
  },
  showAddressSelect: function(){
    this.setData({ addressSelectFlag: true });
  },

  selectRepair(event) {
    const { value } = event.detail;
    let list = [];
    value.forEach(item=>{
      list.push(item.text)
    })
    this.setData({
      'formData.serviceName': list.join(',')
    })
    this.setData({ showTree: false });
  },
  cancelSelect() {
    this.setData({ showTree: false });
  },
  getAddress(){
    const that = this;
    let params = this.data.params;
    addressList(params).then(res=>{
      if(res.code == 200){
        let data = res.rows;
        let list = [];
        data.forEach(item=>{
          list.push({
            text: item.schoolName+item.detailAddress, 
            id: item.id,
            phone: item.phone,
          });
        })
        this.setData({
          addressSelect: list
        });
      }
    })
  },

  confirmSelectedAddress(event) {
    const { value } = event.detail;
    this.setData({
      'formData.schoolName': value.text,
      'formData.phone': value.phone,
      'formData.addresssId': value.id,
      'selectedAddress':value.text
    })
    this.setData({ addressSelectFlag: false });
  },
  cancelSelectAddress() {
    this.setData({ addressSelectFlag: false });
  },

  onChange(event) {
    const { value } = event.detail;
    let id = value[0].id;
    let temp = [
      {
        values: repairList,
        className: 'column1',
      },
      {
        values: repairList[id - 1].children,
        className: 'column2',
      },
    ]
    this.setData({
      columns: temp
    })
  },
  afterRead(event) {
    const that = this;
    const { file } = event.detail;
    // const temp = this.data.fileList;
    // temp.push(file)
    // this.setData({
    //   fileList: temp
    // })
    console.log('afterRead', event)
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: fileUrl + 'upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { contactTable: 'p_order' },
      success(res) {
        let data = JSON.parse(res.data).data;
        console.log('fileUrl', data)
        // 上传完成需要更新 fileList
        const { fileList = [] } = that.data;
        fileList.push({ 
          name: data.name,
          url: data.url,
          fileId: data.fileId
        });
        that.setData({ fileList });
        console.log('fileList', fileList)
      },
      fail(err){
        that.showToast({
          title: '上传失败！',
          icon: 'error',
          mask: true,
        })
      }
    });
  },
  afterRead2(event) {
    const that = this;
    const { file } = event.detail;
    // const temp = this.data.fileList;
    // temp.push(file)
    // this.setData({
    //   fileList: temp
    // })
    console.log('afterRead', event)
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: fileUrl + 'upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { contactTable: 'p_order' },
      success(res) {
        let data = JSON.parse(res.data).data;
        console.log('fileUrl', data)
        // 上传完成需要更新 fileList
        const { fileList2 = [] } = that.data;
        fileList2.push({ 
          name: data.name,
          url: data.url,
          fileId: data.fileId
        });
        that.setData({ fileList2 });
        console.log('fileList2', fileList2)
      },
      fail(err){
        that.showToast({
          title: '上传失败！',
          icon: 'error',
          mask: true,
        })
      }
    });
  },
  showCate: function(){
    this.setData({ showPanel: true });
  },
  onCancel() {
    this.setData({ showPanel: false });
  },
  doClose() {
    this.setData({ showPanel: false });
  },

  onSelectData(e) {
    console.log('onSelect', e.detail);
    this.setData({
      'formData.serviceName': e.detail.name
    })
    this.setData({ showPanel: false });
  },
  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function() {
    //有新的识别内容返回，则会调用此事件
    manager.onStart = function(res) {
      console.log("成功开始录音识别", res)
    }
    manager.onRecognize = (res) => {
      console.log('onRecognize', res);
      let currentData = Object.assign({}, {
                        text: res.result,
                      })
      this.setData({
        recordData: currentData,
      })
      this.scrollToNew();
    }

    // 识别结束事件
    manager.onStop = (res) => {
      console.log('manager.onStop', res);
      let text = res.result

      if(text == '') {
        this.showRecordEmptyTip()
        return
      }

      let lastId = this.data.lastId + 1

      let currentData = Object.assign({}, {
                        text: res.result,
                        translateText: '正在翻译中',
                        id: lastId,
                        voicePath: res.tempFilePath
                      })
      console.log('onStop', currentData);
      // let text =  currentData.text;
      let txt = currentData.text;
      if(this.data.content){
        txt = this.data.content.concat(currentData.text);
      }
      this.setData({
        recordData: currentData,
        recordStatus: 1,
        content: txt,
        'formData.content': txt,
        lastId: lastId,
        bottomButtonDisabled: false,
      })

      this.scrollToNew();
    }

    // 识别错误事件
    manager.onError = (res) => {

      this.setData({
        recording: false,
        bottomButtonDisabled: false,
      })

    }

    // 语音播放开始事件
    wx.onBackgroundAudioPlay(res=>{

      const backgroundAudioManager = wx.getBackgroundAudioManager()
      let src = backgroundAudioManager.src

      this.setData({
        recordDataVoice: src
      })

    })
  },
  /**
   * 按住按钮开始语音识别
   */
  streamRecord: function(e) {
    // console.log("streamrecord" ,e)
    let detail = e.detail || {}
    let buttonItem = detail.buttonItem || {}
    console.log('streamRecord', buttonItem)
    manager.start({
      lang: buttonItem.lang,
    })

    this.setData({
      recordStatus: 0,
      recording: true,
      recordData: {
        // 当前语音输入内容
        create: util.recordTime(new Date()),
        text: '正在聆听中',
        lfrom: buttonItem.lang,
        lto: buttonItem.lto,
      },
    })
    this.scrollToNew();

  },
  /**
   * 重新滚动到底部
   */
  scrollToNew: function() {
    this.setData({
      toView: this.data.toView
    })
  },


  /**
   * 松开按钮结束语音识别
   */
  streamRecordEnd: function(e) {
    let detail = e.detail || {}  // 自定义组件触发事件时提供的detail对象
    let buttonItem = detail.buttonItem || {}
    // 防止重复触发stop函数
    if(!this.data.recording || this.data.recordStatus != 0) {
      console.warn("has finished!")
      return
    }

    manager.stop()

    this.setData({
      bottomButtonDisabled: true,
      recording: false,
    })
  },
  onChooseImage() {
    let max = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('onChooseImage', res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        if (this.data.images.length == MAX_IMG_NUM) {
          this.setData({
            selectPhoto: false
          })
        }
      }
    })
  },
  onDelImage(e) {
    const index = e.currentTarget.dataset.index
    this.data.images.splice(index, 1)
    this.setData({
      images: this.data.images
    })
  },
  onPreviewImage(e) {
    wx.previewImage({
      urls: this.data.images,
      currentTarget: e.target.dataset.imgsrc
    })
  },
  send() {},
  /**
   * 识别内容为空时的反馈
   */
  showRecordEmptyTip: function() {
    this.setData({
      recording: false,
      bottomButtonDisabled: false,
    })
    wx.showToast({
      title: this.data.buttonConf.recognize_nothing,
      icon: 'none',
      duration: 1000,
      success: function (res) {
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getContent(e){
    this.setData({
      'formData.content': e.detail
    })
  },
  handleOrder(){
    let fileList = this.data.fileList;
    let fileList2 = this.data.fileList2;
    let picIds = []
    fileList.forEach(item=>{
      picIds.push(item.fileId)
    })
    fileList2.forEach(item=>{
      picIds.push(item.fileId)
    })
    console.log('picIds', picIds)
    let params = {
      content: this.data.formData.content,
      picIds: picIds,
      serviceName: this.data.formData.serviceName,
      addressId: this.data.formData.addresssId,
    };
    addOrder(params).then(res=>{
      console.log('addOrder', res);
      if(res.code == 200){
        wx.showToast({
          title: '添加订单成功',
          icon: 'success',
          mask: true,
        })
      }
    const loginData = wx.getStorageSync('loginData');
     //用户消息
     if(loginData.subscribeStatus === '0'){
      wx.requestSubscribeMessage({
        tmplIds: ['pCb1mSBy3HK0cU5PjHxMfL497L5rgFFslVo86utkZ8Q'],
        success (res) {
          if(res.errMsg == 'requestSubscribeMessage:ok'){
            let params2 = {
              subscribeStatus: '2'
            };
            saveSubscribeStatus(params2).then(res=>{
              console.log('saveSubscribeStatus', res);

            })
          }
        }
        })
      }
      //跳转到订单列表页面
      wx.redirectTo({
        // url: '/pages/my-order/index',
        url: '/pages/order-list/index',
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let proData = {}
    this.initRecord();
    this.getAddress();
    if(options && options.data){
      proData = JSON.parse(options.data);
    }
    this.setData({
      'formData.schoolName': proData.name,
      'formData.phone': proData.phone,
      'formData.addresssId': proData.id,
      'formData.serviceName': proData.serviceName,
    })
    console.log('data', this.data.formData)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})